package com.bknow.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.bknow.model.ArticleInfo;
import com.bknow.model.CommentInfo;
import com.bknow.model.PageBean;
import com.bknow.model.ResultBean;
import com.bknow.model.SaveLoveInfo;
import com.bknow.model.UserInfo;
import com.bknow.service.ArticleService;

@Controller
public class ArticleController {

	@Autowired
	private ArticleService articleSerivce;

	@PostMapping("upload")
	@ResponseBody
	public ResultBean<Boolean> upload(HttpServletRequest req) throws IOException, ServletException {
		Part part = req.getPart("file");

		String content = req.getParameter("content");
		String articleTitle = req.getParameter("articleTitle");
		String fileName = System.currentTimeMillis() + ".jpg";
		String uId = req.getParameter("uId");
		 //String realPath ="/root/page-brief-knowing/static/upload/";
		String realPath="G:/中级项目/brief-knowing/source/page-brief-knowing/static/upload/";
		String uploadfile = realPath + fileName;
		part.write(uploadfile);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String summry = null;
		if (content.length() < 70)
			summry = content;
		else
			summry = content.substring(0, 70);
		int i = articleSerivce.addArticle(fileName, articleTitle, summry, content, sdf.format(new Date()), 0, 1, 0, 1,
				uId);

		if (i == 1)
			return new ResultBean<Boolean>(200, "success", true);
		else
			return new ResultBean<Boolean>(401, "fail", false);

	}

	@RequestMapping("getAllArticle")
	public @ResponseBody ResultBean<List> getAllArticle(HttpSession hs) {
		List<ArticleInfo> list = articleSerivce.getAllArticle();
		return new ResultBean<List>(200, "success", list);
	}

	@GetMapping("findAllUserByPage") // 文章分页查询
	public @ResponseBody ResultBean<List<ArticleInfo>> findAllUserByPage(int page, int limit) {
		PageBean<List<ArticleInfo>> pb = articleSerivce.findAllArticleByPage(page, limit);
		pb.setMsg("所有文章");
		pb.setStatus(200);
		return pb;
	}

	@GetMapping("findGarbageArticleByPage") // 回收站文章
	public @ResponseBody ResultBean<List<ArticleInfo>> findGarbageArticleByPage(int page, int limit) {
		PageBean<List<ArticleInfo>> pb = articleSerivce.findGarbageArticleByPage(page, limit);
		pb.setMsg("回收站文章");
		pb.setStatus(200);
		return pb;
	}

	@PostMapping("getCommentByArtiId/{article_id}")
	public @ResponseBody ResultBean<List> getCommentByArtiId(@PathVariable("article_id") Integer articleId) {
		List<CommentInfo> list = articleSerivce.getCommentByArtiId(articleId);
		return new ResultBean<List>(200, "success", list);
	}

	@PostMapping("addComment/{uId}/{myComment}/{articleId}")
	public @ResponseBody ResultBean<CommentInfo> addComment(@PathVariable("uId") Integer uId,
			@PathVariable("myComment") String myComment, @PathVariable("articleId") Integer articleId) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-hh-dd");
		CommentInfo info = new CommentInfo(myComment, new ArticleInfo(articleId), new UserInfo(uId),
				sdf.format((new Date())));
		int result = articleSerivce.addComment(info);

		if (result == 1) {
			int CommentTotal = articleSerivce.queryCommentTotal(articleId);
			articleSerivce.updateCommentTotal(CommentTotal + 1, articleId);
			CommentInfo ci = articleSerivce.findCommentById(info.getCommentId());// 查用户，及评论日期
			return new ResultBean<CommentInfo>(200, "success", ci);
		} else {
			return new ResultBean<CommentInfo>(401, "fail", null);
		}
	}

	@PostMapping("getLoveByuId/{uId}")
	public @ResponseBody ResultBean<List> getLoveByuId(@PathVariable("uId") Integer uId) {
		List<SaveLoveInfo> result = articleSerivce.getLoveByuId(uId);
		return new ResultBean<List>(200, "success", result);

	}

	@PostMapping("golove/{uId}/{articleId}")
	public @ResponseBody ResultBean<ArticleInfo> golove(@PathVariable("uId") Integer uId,
			@PathVariable("articleId") Integer articleId) {
		// System.out.println(uId+" "+articleId);
		// 根据uid,articleid查询 是否存在数据

		int count = articleSerivce.queryLoveIsExist(uId, articleId);
		if (count == 1) {
			// 有数据则 看是否点赞
			int is_love = articleSerivce.queryLove(uId, articleId);
			if (is_love == 0) {// 进行点赞 is_love改为1 total_love +1
				articleSerivce.updateLove(uId, articleId, 1);
				int TotalLove = articleSerivce.queryTotalLove(articleId);
				int i = articleSerivce.updateTotalLove(articleId, TotalLove + 1);
				ArticleInfo ai = new ArticleInfo();
				ai.setArticleId(articleId);
				ai.setTotalLove(TotalLove + 1);
				return new ResultBean<ArticleInfo>(201, "success", ai);
			} else {// 取消点赞 is_love改为0 total_love -1
				articleSerivce.updateLove(uId, articleId, 0);
				int TotalLove = articleSerivce.queryTotalLove(articleId);
				int i = articleSerivce.updateTotalLove(articleId, TotalLove - 1);
				ArticleInfo ai = new ArticleInfo();
				ai.setArticleId(articleId);
				ai.setTotalLove(TotalLove - 1);
				return new ResultBean<ArticleInfo>(202, "success", ai);
			}
		} else {
			int result = articleSerivce.addLove(1, uId, articleId);// 没有则插入数据is_love 为1
			int TotalLove = articleSerivce.queryTotalLove(articleId);
			int i = articleSerivce.updateTotalLove(articleId, TotalLove + 1);
			ArticleInfo ai = new ArticleInfo();
			ai.setArticleId(articleId);
			ai.setTotalLove(TotalLove + 1);
			return new ResultBean<ArticleInfo>(200, "success", ai);
		}
	}

	// 文章彻底删除
	@DeleteMapping("deletePatchArticle")
	@ResponseBody
	public ResultBean<Boolean> deletePatchArticle(@RequestBody String ids) {
		int flag = articleSerivce.deletePatchArticle(ids);
		if (flag > 0) {
			return new ResultBean<>(200, "彻底删除成功", true);
		} else {
			return new ResultBean<>(401, "删除失败失败", false);
		}
	}

	// 更改文章状态
	@PostMapping("changeArticleStatus")
	@ResponseBody
	public ResultBean<Boolean> changeArticleStatus(@RequestBody String ids) {
		int flag = articleSerivce.changeArticleStatus(ids);
		JSONObject jsStr = JSONObject.parseObject(ids);
		String status = (String) jsStr.get("status");
		if ("1".equals(status)) {
			return (flag > 0) ? new ResultBean<>(200, "文章恢复成功", true) : new ResultBean<>(401, "文章恢复失败", false);
		} else {
			return (flag >= 0) ? new ResultBean<>(200, "成功丢弃扔到回收站", true) : new ResultBean<>(401, "丢弃失败", false);
		}
	}

}
